const express = require("express");
const app = express();
const cors = require("cors");
const fileUpload = require("express-fileupload");

//数据库
const db = require("./config/mysql.js");
// 引入认证中间件
const authMiddleware = require("./middleware/authMiddleware");
// 引入公共接口
const CommonController = require("./controller/CommonController");

// 允许跨跨域
app.use(cors());

// 静态文件
app.use("/static", express.static("public"));

// 解析json
app.use(express.json());
// 解析urlencoded
app.use(express.urlencoded({ extended: true }));

// 上传文件中间件
app.use(fileUpload({ useTempFiles: true, tempFileDir: "/tmp" }));

// 定义不需要认证的精确路径
// 排除路径 '/users/login'
const EXCLUDED_PATHS = [
  "/",
  "/users/login", // 登录接口
];
const authGate = async (req, res, next) => {
  // req.path 获取请求的 URL 路径，例如 '/users/login'
  const path = req.path;

  // 检查当前请求路径是否在排除列表中
  const shouldExclude = EXCLUDED_PATHS.some((excluded) => excluded === path);

  if (shouldExclude) {
    return next();
  }
  try {
    await authMiddleware(req, res, next);
  } catch (error) {
    // 将错误传递给 Express 的全局错误处理。
    next(error);
  }
};

// 全局认证中间件 ---
app.use(authGate);

// 路由
app.get("/", async (req, res) => {
  res.send("Hello World");
});

// 公共接口
app.use("/common/upload", CommonController.uploadFile);
app.use("/common/getUploadFileUrl", CommonController.getUploadFileUrl);
app.use("/common/delUploadPic", CommonController.delUploadPic);
app.use("/common/getUserListByRoleIds", CommonController.getUserListByRoleIds);

//用户路由
app.use("/users", require("./routes/users.js"));

//食材路由
app.use("/goods", require("./routes/goods.js"));

//分类路由
app.use("/category", require("./routes/category.js"));

// 供应商路由
app.use("/supplier", require("./routes/supplier.js"));

// 仓库路由
app.use("/house", require("./routes/house.js"));

// 库存路由
app.use("/warehousing", require("./routes/warehousing.js"));

// 出库路由
app.use("/outbound", require("./routes/Outbound.js"));

// 采购订单路由
app.use("/procurement-orders", require("./routes/ProcurementOrder.js"));

// 档口路由
app.use("/stalls", require("./routes/stall"));

// 日志路由
app.use("/logs", require("./routes/logs"));

// 账单路由
app.use("/bills", require("./routes/bill"));

//系统设置
app.use("/system", require("./routes/system"));

// 库存路由
app.use("/inventory", require("./routes/inventory.js"));
// 经营状况路由
app.use("/dailyLogs", require("./routes/dailyLogRouter.js"));

// 数据看板路由
app.use("/dataLooks", require("./routes/DataLook.js"));

// 成本统计路由
app.use("/costStatistics", require("./routes/costStatistics.js"));

// 启动服务
app.listen(3000, () => {
  console.log("Server is running on port 3000");
  console.log("http://localhost:3000");
});
